﻿using System;
using System.Linq;
using Soundteller.Bus.Repositories.Interfaces;
using Soundteller.Bus.Services.Interfaces;
using Soundteller.Bus.Model.Interfaces;
using System.Threading;

namespace Soundteller.Bus.Services
{
    public class Publisher : IPublisher
    {
        private readonly IMessageHandlerRepository _subscriberRepository;

        public Publisher(IMessageHandlerRepository subscriberRepository)
        {
            if (subscriberRepository == null) throw new ArgumentNullException("subscriberRepository");

            _subscriberRepository = subscriberRepository;
        }

        public void Publish(IMessage message)
        {
            var messageHandlers = _subscriberRepository.GetByMessageType(message);
            if (!messageHandlers.Any())
                return;

            foreach (var messageHandler in messageHandlers)
            {
                var thread = new Thread(delegate()
                {
                    messageHandler.Handle(message);
                });

                thread.Start();
            }
        }
    }
}
